package ltd.dujiabao.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ltd.dujiabao.commonutils.ResultCode;
import ltd.dujiabao.eduservice.entity.EduSubject;
import ltd.dujiabao.eduservice.entity.subject.ExcelSubjectData;
import ltd.dujiabao.eduservice.entity.subject.PrimarySubject;
import ltd.dujiabao.eduservice.entity.subject.SecondarySubject;
import ltd.dujiabao.eduservice.mapper.EduSubjectMapper;
import ltd.dujiabao.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.dujiabao.servicebase.exception.MyException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author dujiabao
 * @since 2021-04-21
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
  @Override
  public List<PrimarySubject> getSubjectsTree() {
    // 获取所有一级列表在数据库中的存储
    QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
    wrapper.eq("parent_id", "0");
    List<EduSubject> primaryList = list(wrapper);

    // 获取所有一级列表在数据库中的存储
    wrapper = new QueryWrapper<>();
    wrapper.ne("parent_id", "0");
    List<EduSubject> secondaryList = list(wrapper);

    // 通过map暂存结果，方便二级列表查找
    Map<String, PrimarySubject> map = new HashMap<>();
    List<PrimarySubject> result = new ArrayList<>();

    for (EduSubject subject : primaryList) {
      PrimarySubject primarySubject = new PrimarySubject(subject.getId(), subject.getTitle());
      result.add(primarySubject);
      map.put(subject.getId(), primarySubject);
    }
    // 为二级列表找家
    for (EduSubject subject : secondaryList) {
      PrimarySubject primarySubject = map.get(subject.getParentId());
      primarySubject.addSecondarySubject(new SecondarySubject(subject.getId(), subject.getTitle()));
    }
    return result;
  }

  /**
   * 通过excel导入课程分类的方法
   * @param file
   * @return
   */
  @Override
  public boolean saveBatchByExcel(MultipartFile file) {
    try {
      EasyExcel.read(file.getInputStream(), ExcelSubjectData.class, new EduSubjectReadExcelListener()).sheet().doRead();
      return true;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 导入课程的监听器，内部类
   */
  public class EduSubjectReadExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    /**
     * 一行一行读，一行一行处理
     *
     * @param excelSubjectData
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
      if (excelSubjectData == null) throw new MyException(ResultCode.FAILURE, "添加失败");
      String primaryClass = excelSubjectData.getPrimaryClass();
      String secondaryClass = excelSubjectData.getSecondaryClass();
      // 获取一级分类，查询是否存在，不存在才创建
      EduSubject primarySubject = getSubject(primaryClass, "0");
      if (primarySubject == null) {
        primarySubject = new EduSubject().setTitle(primaryClass).setParentId("0");  // 因为不存在，所以要创建一个新的
        save(primarySubject);  // 保存，在保存的过程中，会将id值也保存在这个对象中
      }
      // 获取二级分类，查询是否存在，不存在才创建
      EduSubject secondarySubject = getSubject(secondaryClass, primarySubject.getId());
      if (secondarySubject == null) {
        secondarySubject = new EduSubject().setTitle(secondaryClass).setParentId(primarySubject.getId());
        save(secondarySubject);
      }
    }

    public EduSubject getSubject(String secondaryClass, String primaryId) {
      QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
      wrapper.eq("title", secondaryClass).eq("parent_id", primaryId);
      return getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
  }
}
